import ApiV1WxMessageSave_post from "@/api/ApiV1WxMessageSave_post"; // TAV
import { IRawMsg } from "@/chatlog_types/IRawMsg";
import { MsgTypeEnum } from "@/chatlog_types/MsgTypeEnum";
import { show_raw_jsons } from "@/utils/show_raw_jsons";
import { Chat } from "../Chat";
import { ui } from "../Chat/ui";
import { RawMsgShareType } from "./RawMsgShareType";
import { tasks_keeper } from "@/mgr/tasks/instance";
import { create_msg_commit_job } from "@/mgr/chat/create_msg_commit_job";
export namespace RawMsgType {
  function info(text: string, desc: string = text): Info { return { text, desc }; }
  export interface Info {
    text: string;
    desc: string;
  }
  export const Value = MsgTypeEnum;
  export type Value = MsgTypeEnum;
  export const Infos: Record<Value, Info> = {
    [Value.Text]: info('文本'),
    [Value.Image]: info('图片'),
    [Value.Voice]: info('语音'),
    [Value.NameCard]: info('名片'),
    [Value.Video]: info('视频'),
    [Value.Emoticon]: info('动画表情'),
    [Value.Share]: info('分享'),
    [Value.VoiceCall]: info('语音通话'),
    [Value.SysMsg]: info('系统消息'),
  };
  export const readType = (msg: IRawMsg): Chat.MessageType => {
    switch (msg.type as Value) {
      case Value.SysMsg: return Chat.MessageType.system
      case Value.Text: return Chat.MessageType.text
      case Value.Share: return RawMsgShareType.readType(msg);
      case Value.Image: return Chat.MessageType.img
    }
    return Chat.MessageType.text
  }
  export const readContent = (msg: IRawMsg): string => {
    const type = msg.type as Value;
    switch (type) {
      case Value.SysMsg:
      case Value.Text:
        return msg.content || ""
      case Value.Share:
        return RawMsgShareType.readContent(msg)
      case Value.Emoticon:
      case Value.Image:
      case Value.Voice:
      case Value.VoiceCall:
      case Value.Video:
        return `[${Infos[type].text}]`;
    }
    const type_name =
      Infos[msg.type as Value]?.text ??
      Value[msg.type as Value] ??
      `type_${msg.type}`
    return `[${type_name}] ${JSON.stringify(msg)}`;
  }

  export const renderAfterBubble = (msg: IRawMsg | undefined | null): ui.UINode[] | ui.UINode => {
    if (!msg) return

    const bottom = ui.node('div', {
      className: 'dev_only',
      style: { display: 'inline-flex', gap: `5px`, flexDirection: 'row', paddingTop: '5px' }
    }, [
      ui.node("button", { onclick: () => show_raw_jsons([msg]) }, "原始数据"),
      ui.node("button", {
        onclick: () => {
          const id = tasks_keeper().unshift(create_msg_commit_job(msg))
          if (!tasks_keeper().auto_submit) tasks_keeper().start(id)
        }
      }, "提交")
    ])

    switch (msg.type as Value) {
      case Value.Share:
        return RawMsgShareType.renderAfterBubble(msg, bottom)
      default:
        return bottom
    }
  }
}
